package com.iqilu.ksd.activity;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Color;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.os.Handler;
import android.os.Vibrator;
import android.support.annotation.Nullable;
import android.support.v4.content.ContextCompat;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.view.animation.AlphaAnimation;
import android.view.animation.Animation;
import android.view.animation.AnimationSet;
import android.view.animation.AnimationUtils;
import android.view.animation.LinearInterpolator;
import android.view.animation.TranslateAnimation;
import android.widget.Chronometer;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.facebook.drawee.view.SimpleDraweeView;
import com.google.gson.reflect.TypeToken;
import com.iqilu.ksd.MyApplication;
import com.iqilu.ksd.R;
import com.iqilu.ksd.adapter.WinnerAdapter;
import com.iqilu.ksd.bean.PrizeinfoBean;
import com.iqilu.ksd.bean.ShakeBean;
import com.iqilu.ksd.bean.ShakeResultBean;
import com.iqilu.ksd.bean.UserBean;
import com.iqilu.ksd.bean.WinnerBean;
import com.iqilu.ksd.constant.Api;
import com.iqilu.ksd.constant.Config;
import com.iqilu.ksd.constant.ShakeStatus;
import com.iqilu.ksd.listener.ShakeListener;
import com.iqilu.ksd.utils.ConvertUtils;
import com.iqilu.ksd.utils.JSONUtils;
import com.iqilu.ksd.utils.ScreenUtils;
import com.iqilu.ksd.widget.LigDialog;
import com.jaeger.library.StatusBarUtil;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.StringCallback;

import org.w3c.dom.Text;

import java.lang.reflect.Array;
import java.util.ArrayList;
import java.util.List;

import okhttp3.Call;
import okhttp3.Request;

/**
 * Created by Coofee on 2016/11/22.
 */

public class ShakeActivity extends BaseActivity {

    private static final String TAG = "ShakeActivity";

    private UserBean user;
    private ShakeBean data = null;
    private LigDialog ligDialog;

    private ShakeListener mShakeListener = null;
    private Vibrator mVibrator;

    private int status = ShakeStatus.NOT_START;
    private int id;
    private String title;
    private String secret;
    private static final int REQUEST_CODE_LOGIN = 1001;

    private RelativeLayout layMain;
    private ImageView imgTopLine;
    private ImageView imgBottomLine;
    private RelativeLayout layShakeTop;
    private RelativeLayout layShakeBottom;
    private RelativeLayout layResult;
    private SimpleDraweeView imgResult;
    private TextView tvResult;
    private LinearLayout layLoading;
    private ImageView imgLoading;
    private TextView tvTitle;
    private ImageView btRule;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_shake);
        StatusBarUtil.setTranslucentForImageView(this,Config.STATUSBAR_ALPHA,layMain);
        initView();
        mVibrator = (Vibrator) getSystemService(VIBRATOR_SERVICE);
        user = ((MyApplication) getApplication()).getUser();
        id = getIntent().getIntExtra("id",0);
        setAnimation();
        initMargin();
        if (user != null && user.getId() > 0) {
            getContent();
        } else {
            startActivityForResult(new Intent(this, LoginActivity.class), REQUEST_CODE_LOGIN);
        }
    }

    private void initView() {
        layMain = getView(R.id.lay_main);
        imgTopLine = getView(R.id.img_top_line);
        imgBottomLine = getView(R.id.img_bottom_line);
        layShakeTop = getView(R.id.lay_shake_top);
        layShakeBottom = getView(R.id.lay_shake_bottom);
        layResult = getView(R.id.lay_result);
        imgResult = getView(R.id.img_result);
        tvResult = getView(R.id.tv_result);
        layLoading = getView(R.id.lay_loading);
        imgLoading = getView(R.id.img_loading);
        tvTitle = getView(R.id.tv_title);
        btRule = getView(R.id.bt_rule);
        setZHTypeface(tvTitle);
    }

    private void initMargin() {
        int height = ScreenUtils.getScreenHeight(this);
        RelativeLayout.LayoutParams params = (RelativeLayout.LayoutParams) layLoading.getLayoutParams();
        params.setMargins(0, 0, 0, ConvertUtils.px2dp(this, height / 3));
        layLoading.setLayoutParams(params);

        RelativeLayout.LayoutParams params2 = (RelativeLayout.LayoutParams) layResult.getLayoutParams();
        params2.setMargins(0, 0, 0, ConvertUtils.px2dp(this, height / 4));
        layResult.setLayoutParams(params2);
    }

    private void initShake() {
        mShakeListener = new ShakeListener(this);
        mShakeListener.setOnShakeListener(new ShakeListener.OnShakeListener() {
            public void onShake() {
                startAnim();  //开始 摇一摇手掌动画
                mShakeListener.stop();
                startVibrato(); //开始 震动
                new Handler().postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        mVibrator.cancel();
                        startRock();
                    }
                }, 2000);
            }
        });
    }

    private void setAnimation() {
        Animation rotateAnimation = AnimationUtils.loadAnimation(this, R.anim.loading_shake);
        LinearInterpolator lin = new LinearInterpolator();
        rotateAnimation.setInterpolator(lin);
        imgLoading.setAnimation(rotateAnimation);
    }

    private void startVibrato() {
        MediaPlayer player;
        player = MediaPlayer.create(this, R.raw.shake_start);
        player.setLooping(false);
        player.start();
        //定义震动
        mVibrator.vibrate(new long[]{500, 200, 500, 200}, -1); //第一个｛｝里面是节奏数组， 第二个参数是重复次数，-1为不重复，非-1俄日从pattern的指定下标开始重复
    }

    private void playEndMusic() {
        MediaPlayer player;
        player = MediaPlayer.create(this, R.raw.shake_end);
        player.setLooping(false);
        player.start();
    }

    private void getContent() {
        String url = Api.URL_ROCK_INFO + "?rockid="+id;
        OkHttpUtils.get().url(url).tag(this).build().execute(new StringCallback() {
            @Override
            public void onBefore(Request request, int id) {
                super.onBefore(request, id);
                ligDialog = new LigDialog(ShakeActivity.this, getString(R.string.loading));
                ligDialog.show();
            }

            @Override
            public void onError(Call call, Exception e, int id) {
                ligDialog.dismiss();
            }

            @Override
            public void onResponse(String response, int id) {
                ligDialog.dismiss();
                data = JSONUtils.requestDetail(response, "data", ShakeBean.class);
                tvTitle.setText(data.getTitle());
                btRule.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        Intent intent = new Intent(ShakeActivity.this,ADActivity.class);
                        intent.putExtra("title",data.getTitle());
                        intent.putExtra("adUrl",data.getUrl());
                        startActivity(intent);
                    }
                });
                Log.i(TAG,"begin=====>"+data.getBegin());
                if(data.getBegin() == 0){ //未开始
                    showBeginAlert();
                }else if(data.getBegin() == 1){ //正在进行
                    status = ShakeStatus.START;
                    initShake();
                }else if(data.getBegin() == 2){ //已经结束
                    showEndAlert();
                }else { // 已经结束十分钟
                    getWinnerList();
                }
            }
        });
    }

    //开始摇奖
    private void startRock() {
        if (data == null) return;
        String url = Api.URL_ROCK;
        Log.i(TAG, "url=" + url);
        OkHttpUtils.post().url(url).addParams("rockid", "" + id).tag(this).build().execute(new StringCallback() {
            @Override
            public void onBefore(Request request, int id) {
                super.onBefore(request, id);
                layLoading.setVisibility(View.VISIBLE);
            }

            @Override
            public void onError(Call call, Exception e, int id) {
                Log.i(TAG, "onError...");
                layLoading.setVisibility(View.GONE);
                playEndMusic();
                mShakeListener.start();
                Toast.makeText(ShakeActivity.this, R.string.shake_title_not_win, Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onResponse(String response, int id) {
                Log.i(TAG, "response=" + response);
                layLoading.setVisibility(View.GONE);
                playEndMusic();
                ShakeResultBean result = JSONUtils.requestDetail(response, "data", ShakeResultBean.class);
                afterRock(result);
            }
        });
    }

    //即将开始
    private void showBeginAlert(){
        AlertDialog dialog = new AlertDialog.Builder(this,R.style.live_dialog).create();
        dialog.show();
        Window window = dialog.getWindow();
        window.setContentView(R.layout.popu_shake_begin);
        TextView tvTitle = (TextView) window.findViewById(R.id.tv_title);
        setZHTypeface(tvTitle);
        tvTitle.setText(""+data.getTitle());
    }

    //已经结束
    private void showEndAlert(){
        AlertDialog dialog = new AlertDialog.Builder(this,R.style.live_dialog).create();
        dialog.show();
        Window window = dialog.getWindow();
        window.setContentView(R.layout.popu_shake_end);
        TextView tvTitle = (TextView) window.findViewById(R.id.tv_title);
        setZHTypeface(tvTitle);
        tvTitle.setText(""+data.getTitle());
    }

    //中奖
    private void showWinAlert(final PrizeinfoBean data){
        final AlertDialog dialog = new AlertDialog.Builder(this,R.style.live_dialog).create();
        dialog.setCanceledOnTouchOutside(false);
        dialog.show();
        Window window = dialog.getWindow();
        window.setContentView(R.layout.popu_shake_win);
        TextView tvTitle = (TextView) window.findViewById(R.id.tv_title);
        TextView tvPrize = (TextView) window.findViewById(R.id.tv_prize);
        TextView tvDesc = (TextView) window.findViewById(R.id.tv_desc);
        final TextView tvTime = (TextView) window.findViewById(R.id.tv_time);
        ImageView btWin = (ImageView) window.findViewById(R.id.bt_win);
        ImageView btClose = (ImageView) window.findViewById(R.id.bt_close);
        setZHTypeface(tvPrize);
        setZHTypeface(tvTitle);
        setZHTypeface(tvTime);
        setZHTypeface(tvDesc);
        tvTitle.setText(""+data.getTitle());
        tvPrize.setText(""+data.getLevel());
        btWin.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dialog.dismiss();
                Intent intent = new Intent(ShakeActivity.this,ShakeResultActivity.class);
                intent.putExtra("title",data.getTitle());
                intent.putExtra("thumb",data.getThumb());
                intent.putExtra("secret",data.getSecret());
                startActivity(intent);
            }
        });
        btClose.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dialog.dismiss();
            }
        });
        CountDownTimer countDownTimer = new CountDownTimer(600000,1000) {
            @Override
            public void onTick(long millisUntilFinished) {
                long left = millisUntilFinished / 1000;
                tvTime.setText("0"+ left / 60 +"："+left % 60);
            }

            @Override
            public void onFinish() {
                dialog.dismiss();
            }
        };
        countDownTimer.start();
        dialog.setOnDismissListener(new DialogInterface.OnDismissListener() {
            @Override
            public void onDismiss(DialogInterface dialog) {
                mShakeListener.start();
            }
        });
    }

    //未中奖
    private void showNotWinAlert(PrizeinfoBean data){
        final AlertDialog dialog = new AlertDialog.Builder(this,R.style.live_dialog).create();
        dialog.show();
        Window window = dialog.getWindow();
        window.setContentView(R.layout.popu_shake_not_win);
        TextView tvTitle = (TextView) window.findViewById(R.id.tv_title);
        SimpleDraweeView imgThumb = (SimpleDraweeView) window.findViewById(R.id.img_thumb);
        ImageView btClose = (ImageView) window.findViewById(R.id.bt_close);
        ImageView btRetry = (ImageView) window.findViewById(R.id.bt_retry);
        setZHTypeface(tvTitle);
        tvTitle.setText(""+data.getNoprizetip());
        imgThumb.setImageURI(Uri.parse(""+data.getThumb()));
        btClose.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dialog.dismiss();
            }
        });
        btRetry.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dialog.dismiss();
            }
        });

        dialog.setOnDismissListener(new DialogInterface.OnDismissListener() {
            @Override
            public void onDismiss(DialogInterface dialog) {
                mShakeListener.start();
            }
        });
    }

    private void afterRock(ShakeResultBean result){
        if(result.getBegin() == 0){
            showBeginAlert();
        }else if(result.getBegin() == 1){
            if(result.getPrize() == 1){ //中奖
                showWinAlert(result.getPrizeinfo());
            }else {
                showNotWinAlert(result.getPrizeinfo());
            }
        }else if(result.getBegin() == 2){
            showEndAlert();
        }else {
            getWinnerList();
        }
    }

//    private void afterRock(ShakeResultBean result) {
//        Intent intent = new Intent(this, ShakeResultActivity.class);
//        if (result != null) {
//            intent.putExtra("title", result.getTitle());
//            intent.putExtra("secret", result.getSecret());
//        }
//        intent.putExtra("startTime", data.getStart());
//        if (result != null && result.getBegin() == 1) { //正在进行
//            if (result.getPrize() == 1) { //中奖
//                if (!TextUtils.isEmpty(result.getPrizeinfo().getThumb())) {
//                    imgResult.setImageURI(Uri.parse(result.getPrizeinfo().getThumb()));
//                } else {
//                    imgResult.setImageURI("res://" + this.getPackageName() + "/" + R.drawable.shake_win);
//                }
//                status = ShakeStatus.WIN;
//                title = result.getPrizeinfo().getTitle();
//                secret = result.getSecret();
//                tvResult.setText("" + result.getPrizeinfo().getTitle());
//                tvResult.setTextColor(ContextCompat.getColor(this, R.color.title_orange));
//                new Handler().postDelayed(new Runnable() {
//                    @Override
//                    public void run() {
//                        layResult.setVisibility(View.GONE);
//                        mShakeListener.start();
//                        Intent intent = new Intent(ShakeActivity.this, ShakeResultActivity.class);
//                        intent.putExtra("status", status);
//                        intent.putExtra("title", title);
//                        intent.putExtra("secret", secret);
//                        startActivity(intent);
//                    }
//                }, 1000);
//            } else {//未中奖
//                status = ShakeStatus.NOT_WIN;
//                imgResult.setImageURI("res://" + this.getPackageName() + "/" + R.drawable.shake_not_win);
//                tvResult.setText(getString(R.string.shake_title_not_win));
//                tvResult.setTextColor(Color.BLACK);
//                new Handler().postDelayed(new Runnable() {
//                    @Override
//                    public void run() {
//                        if (layResult.getVisibility() == View.VISIBLE) {
//                            layResult.setVisibility(View.GONE);
//                            mShakeListener.start();
//                        }
//                    }
//                }, 2000);
//            }
////            layoutResult.setAlpha(0.0f);
//            layResult.setVisibility(View.VISIBLE);
//            AlphaAnimation animation = new AlphaAnimation(0.0f, 1.0f);
//            animation.setDuration(500);
//            layResult.startAnimation(animation);
//        } else if (result != null && result.getBegin() == 0) { //还未开始
//            status = ShakeStatus.NOT_START;
//            intent.putExtra("status", status);
//            startActivity(intent);
//            finish();
//        } else { // 默认已经结束
//            status = ShakeStatus.END;
//            intent.putExtra("status", status);
//            startActivity(intent);
//            finish();
//        }
//    }

    //获取获奖名单
    private void getWinnerList(){
        String url = Api.URL_ROCK_WINNER + "?rockid="+id;
        Log.i(TAG,"getWinnerList url="+url);
        OkHttpUtils.get().url(url).tag(this).build().execute(new StringCallback() {
            @Override
            public void onError(Call call, Exception e, int id) {

            }

            @Override
            public void onResponse(String response, int id) {
                ArrayList<WinnerBean> list = JSONUtils.requestList(response,"data",new TypeToken<ArrayList<WinnerBean>>(){});
                showWinnerAlert(list);
            }
        });
    }

    private void showWinnerAlert(ArrayList<WinnerBean> list){
        AlertDialog dialog = new AlertDialog.Builder(ShakeActivity.this,R.style.live_dialog).create();
        dialog.show();
        Window window = dialog.getWindow();
        window.setContentView(R.layout.popu_shake_winner);
        ListView lvList = (ListView) window.findViewById(R.id.lv_list);
        WinnerAdapter adapter = new WinnerAdapter(this,list);
        lvList.setAdapter(adapter);
    }

    public void startAnim() {   //定义摇一摇动画
        AnimationSet animup = new AnimationSet(true);
        TranslateAnimation mytranslateanimup0 = new TranslateAnimation(Animation.RELATIVE_TO_SELF, 0f, Animation.RELATIVE_TO_SELF, 0f, Animation.RELATIVE_TO_SELF, 0f, Animation.RELATIVE_TO_SELF, -0.8f);
        mytranslateanimup0.setDuration(1000);
        TranslateAnimation mytranslateanimup1 = new TranslateAnimation(Animation.RELATIVE_TO_SELF, 0f, Animation.RELATIVE_TO_SELF, 0f, Animation.RELATIVE_TO_SELF, 0f, Animation.RELATIVE_TO_SELF, +0.8f);
        mytranslateanimup1.setDuration(1000);
        mytranslateanimup1.setStartOffset(1000);
        animup.addAnimation(mytranslateanimup0);
        animup.addAnimation(mytranslateanimup1);
        imgTopLine.setVisibility(View.VISIBLE);
        layShakeTop.startAnimation(animup);
//        shakeBg.setVisibility(View.VISIBLE);
        mytranslateanimup1.setAnimationListener(new TranslateAnimation.AnimationListener() {
            @Override
            public void onAnimationStart(Animation animation) {

            }

            @Override
            public void onAnimationEnd(Animation animation) {
                imgTopLine.setVisibility(View.GONE);
//                shakeBg.setVisibility(View.GONE);
            }

            @Override
            public void onAnimationRepeat(Animation animation) {

            }
        });

        AnimationSet animdn = new AnimationSet(true);
        TranslateAnimation mytranslateanimdn0 = new TranslateAnimation(Animation.RELATIVE_TO_SELF, 0f, Animation.RELATIVE_TO_SELF, 0f, Animation.RELATIVE_TO_SELF, 0f, Animation.RELATIVE_TO_SELF, +0.8f);
        mytranslateanimdn0.setDuration(1000);
        TranslateAnimation mytranslateanimdn1 = new TranslateAnimation(Animation.RELATIVE_TO_SELF, 0f, Animation.RELATIVE_TO_SELF, 0f, Animation.RELATIVE_TO_SELF, 0f, Animation.RELATIVE_TO_SELF, -0.8f);
        mytranslateanimdn1.setDuration(1000);
        mytranslateanimdn1.setStartOffset(1000);
        animdn.addAnimation(mytranslateanimdn0);
        animdn.addAnimation(mytranslateanimdn1);
        imgBottomLine.setVisibility(View.VISIBLE);
        layShakeBottom.startAnimation(animdn);
        mytranslateanimdn1.setAnimationListener(new TranslateAnimation.AnimationListener() {
            @Override
            public void onAnimationStart(Animation animation) {

            }

            @Override
            public void onAnimationEnd(Animation animation) {
                imgBottomLine.setVisibility(View.GONE);
            }

            @Override
            public void onAnimationRepeat(Animation animation) {

            }
        });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                case REQUEST_CODE_LOGIN:
                    user = ((MyApplication) getApplication()).getUser();
                    getContent();
                    break;
                default:
                    break;
            }
        } else {
            finish();
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        if(status != ShakeStatus.NOT_START) {
            initShake();
        }
    }

    @Override
    protected void onPause() {
        super.onPause();
        if (mShakeListener != null) {
            mShakeListener.stop();
        }
    }

    @Override
    protected void onStop() {
        super.onStop();
        if (mShakeListener != null) {
            mShakeListener.stop();
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
    }


}
